package com.haixiaoke.callback.order.controller;

import cn.hutool.core.util.ObjectUtil;
import com.haixiaoke.saas.common.utils.GsonUtil;
import com.haixiaoke.saas.common.weChat.domain.ParseParam;
import com.haixiaoke.saas.common.weChat.domain.RefundParam;
import com.haixiaoke.saas.common.weChat.domain.RefundReqInfo;
import com.haixiaoke.saas.common.weChat.service.WeChatService;
import com.haixiaoke.saas.common.weChat.util.WeChatUtils;
import com.haixiaoke.saas.department.domain.WechatAccount;
import com.haixiaoke.saas.department.service.IWechatAccountService;
import com.haixiaoke.saas.system.framework.manager.AsyncManager;
import com.haixiaoke.saas.system.framework.manager.factory.AsyncFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @Author panda
 * @Date 2024/4/15
 **/
@Slf4j
@RestController
@RequestMapping("/callback/order/apartment")
public class CallbackOrderController {

    @Autowired
    private WeChatService weChatService;
    @Autowired
    private IWechatAccountService wechatAccountService;

    /**
     * 公寓订单支付回调
     *
     * @param parseParam
     * @throws Exception
     */
    @RequestMapping("/pay")
    public String pay(@RequestBody ParseParam parseParam) {
        try {
            log.info("微信支付回调参数：{}", GsonUtil.toJson(parseParam));
            WechatAccount account = wechatAccountService.selectWechatAccountByTenantId(parseParam.getAttach());
            // 签名验证
            if (!weChatService.signCheck(parseParam, account.getAccountApiKey())) {
                log.info("签名验证失败：查询的商户id：{}，回调的订单id：{}，订单的组织id：{}", GsonUtil.toJson(account), parseParam.getOutTradeNo(), parseParam.getAttach());
                return parseParam.resultFail(WeChatUtils.FAIL, "签名失败");
            }
            //异步处理回调业务
            AsyncManager.me().execute(AsyncFactory.weChatCallbackOrderPay(parseParam));
        } catch (Exception e) {
            log.error("小程序支付--公寓订单回调发生了错误：{}", e.getLocalizedMessage(), e);
            return parseParam.resultFail(WeChatUtils.FAIL, e.getLocalizedMessage());
        }
        return parseParam.resultSuccess();
    }

    /**
     * 取消预订订单退款回调
     * @param refundParam
     * @return
     */
    @RequestMapping("/cancelReservation")
    public String cancelReservation(@RequestBody RefundParam refundParam) {
        try {
            WechatAccount account = wechatAccountService.selectWechatAccountByAccountId(refundParam.getMchId());
            log.info("微信退款回调参数：{},{}", GsonUtil.toJson(refundParam), GsonUtil.toJson(account));
            if (ObjectUtil.isEmpty(account)) {
                log.error("商户号数据异常");
                return refundParam.resultFail(WeChatUtils.FAIL, "商户号异常，查询不到数据");
            }
            refundParam.setMchKey(account.getAccountApiKey());
            RefundReqInfo reqInfo = weChatService.getReqInfo(refundParam);
            if (ObjectUtil.isEmpty(reqInfo)) {
                log.error("req_info，解密数据获取异常");
                return refundParam.resultFail(WeChatUtils.FAIL, "解密数据获取异常");
            }
            //异步处理回调业务
            AsyncManager.me().execute(AsyncFactory.weChatCallbackCancelReservation(refundParam, reqInfo));
        } catch (Exception e) {
            log.error("取消预订订单退款--公寓订单回调发生了错误：{}", e.getLocalizedMessage(), e);
            return refundParam.resultFail(WeChatUtils.FAIL, e.getLocalizedMessage());
        }
        return refundParam.resultSuccess();
    }

    /**
     * 补缴订单支付回调
     *
     * @param parseParam
     * @throws Exception
     */
    @PostMapping("/supplementaryPayment")
    public String supplementaryPayment(@RequestBody ParseParam parseParam) {
        try {
            log.info("微信支付回调参数：{}", GsonUtil.toJson(parseParam));
            WechatAccount account = wechatAccountService.selectWechatAccountByTenantId(parseParam.getAttach());
            // 签名验证
            if (!weChatService.signCheck(parseParam, account.getAccountApiKey())) {
                log.info("签名验证失败：查询的商户id：{}，回调的订单id：{}，订单的组织id：{}", GsonUtil.toJson(account), parseParam.getOutTradeNo(), parseParam.getAttach());
                return parseParam.resultFail(WeChatUtils.FAIL, "签名失败");
            }
            //异步处理回调业务
            AsyncManager.me().execute(AsyncFactory.weChatCallbackOrderSupplementaryPay(parseParam));
        } catch (Exception e) {
            log.error("小程序支付--公寓订单回调发生了错误：{}", e.getLocalizedMessage(), e);
            return parseParam.resultFail(WeChatUtils.FAIL, e.getLocalizedMessage());
        }
        return parseParam.resultSuccess();
    }

    /**
     * 退房订单退款回调
     * @param refundParam
     * @return
     */
    @PostMapping("/checkOut")
    public String checkOut(@RequestBody RefundParam refundParam) {
        try {
            WechatAccount account = wechatAccountService.selectWechatAccountByAccountId(refundParam.getMchId());
            log.info("微信退款回调参数：{},{}", GsonUtil.toJson(refundParam), GsonUtil.toJson(account));
            if (ObjectUtil.isEmpty(account)) {
                log.error("商户号数据异常");
                return refundParam.resultFail(WeChatUtils.FAIL, "商户号异常，查询不到数据");
            }
            refundParam.setMchKey(account.getAccountApiKey());
            RefundReqInfo reqInfo = weChatService.getReqInfo(refundParam);
            if (ObjectUtil.isEmpty(reqInfo)) {
                log.error("req_info，解密数据获取异常");
                return refundParam.resultFail(WeChatUtils.FAIL, "解密数据获取异常");
            }
            //异步处理回调业务
            AsyncManager.me().execute(AsyncFactory.weChatCallbackCheckOut(refundParam, reqInfo));
        } catch (Exception e) {
            log.error("取消预订订单退款--公寓订单回调发生了错误：{}", e.getLocalizedMessage(), e);
            return refundParam.resultFail(WeChatUtils.FAIL, e.getLocalizedMessage());
        }
        return refundParam.resultSuccess();
    }
}
